package com.neusoft.elm.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.neusoft.elm.dao.CartDao;
import com.neusoft.elm.dao.impl.CartDaoImpl;
import com.neusoft.elm.po.Cart;
import com.neusoft.elm.service.CartService;
import com.neusoft.elm.util.DBUtil;

public class CartServiceImpl implements CartService {
    
    @Override
    public List<Cart> listCart(Cart cart) {
        List<Cart> list = new ArrayList<>();
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            list = dao.listCart(cart);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public int saveCart(Cart cart) {
        int result = 0;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            result = dao.saveCart(cart);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int saveOrUpdateCart(Cart cart) {
        int result = 0;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            result = dao.saveOrUpdateCart(cart);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public boolean syncCartToDevices(String userId) {
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            List<Cart> unsyncedCarts = dao.getUnsyncedCarts(userId);
            if (!unsyncedCarts.isEmpty()) {
                List<Integer> cartIds = new ArrayList<>();
                for (Cart cart : unsyncedCarts) {
                    cartIds.add(cart.getCartId());
                }
                dao.markCartsSynced(cartIds);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close();
        }
        return true;
    }

    @Override
    public List<Cart> getUnsyncedCarts(String userId) {
        List<Cart> list = new ArrayList<>();
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            list = dao.getUnsyncedCarts(userId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public boolean mergeCartFromDevices(String userId, String currentDeviceId) {
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            
            // 获取所有设备的购物车数据
            Cart searchCart = new Cart();
            searchCart.setUserId(userId);
            List<Cart> allCarts = dao.listCart(searchCart);
            
            // 按照食品ID和商家ID分组合并
            Map<String, Cart> mergedCarts = new HashMap<>();
            
            for (Cart cart : allCarts) {
                String key = cart.getFoodId() + "_" + cart.getBusinessId();
                if (mergedCarts.containsKey(key)) {
                    Cart existing = mergedCarts.get(key);
                    // 保留最新的更新时间和数量累加
                    if (cart.getUpdateTime().after(existing.getUpdateTime())) {
                        existing.setQuantity(existing.getQuantity() + cart.getQuantity());
                        existing.setUpdateTime(cart.getUpdateTime());
                        existing.setDeviceId(currentDeviceId);
                    }
                } else {
                    cart.setDeviceId(currentDeviceId);
                    mergedCarts.put(key, cart);
                }
            }
            
            // 清空用户购物车并重新插入合并后的数据
            dao.clearUserCart(userId);
            
            for (Cart cart : mergedCarts.values()) {
                cart.setCartId(null); // 重新生成ID
                cart.setSyncStatus(1); // 标记为已同步
                dao.saveCart(cart);
            }
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close();
        }
    }

    @Override
    public int clearUserCart(String userId) {
        int result = 0;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            result = dao.clearUserCart(userId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int removeCart(Cart cart) {
        int result = 0;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            result = dao.removeCart(cart);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int updateCart(Cart cart) {
        int result = 0;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            result = dao.updateCart(cart);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return result;
    }
}